import React, { useEffect, useState } from "react";
import { Search, Tag } from "react-vant";

// 默认取
const lists = JSON.parse(localStorage.getItem("historyList") || "[]");

const Index: React.FC = () => {
  const [historyList, setHistoryList] = useState<string[]>(lists);

  const onSearch = (value: string) => {
    setHistoryList([...new Set([value, ...historyList])]);
  };

  //依赖
  useEffect(() => {
    // 存储
    localStorage.setItem("historyList", JSON.stringify(historyList));
  }, [historyList]);

  const isHistoryListExist = historyList.length === 0;

  return (
    <div>
      <Search onSearch={onSearch}></Search>
      <div style={{ padding: 4 }}>
        <h2
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <span>搜索记录</span>
          <span onClick={() => setHistoryList([])}>删除</span>
        </h2>
        {isHistoryListExist ? (
          <div>暂无用户搜索记录</div>
        ) : (
          <div>
            {historyList.map((v, i) => {
              return (
                <Tag type="primary" style={{ margin: 4 }} key={i}>
                  {v}
                </Tag>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

export default Index;
